<template>
	<uni-nav-bar fixed="true" statusBar="true" border="false" left-icon="left" title="订单" @clickLeft="back"></uni-nav-bar>
	<view class="container">
		<view class="sticky" :style="{'top':showNavTop+'px'}">
			<view><text :class="navIndex==0?'mr100 active':'mr100'" @click="checkIndex(0)">收款订单</text><text :class="navIndex==1?'active':''" @click="checkIndex(1)">支出订单</text></view>
			<view class="is-flex p010">
				<view class="is-flex">
					<picker mode="date" fields="month"  :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
						<view class="uni-input">{{date}}</view>
					</picker>
					<uni-icons type="down" size="20" color="#666"></uni-icons>
				</view>
				<view class="flex1">
					<uni-search-bar v-model="param.keyword" radius="5" placeholder="输入手机号、线路、行程查询" clearButton="auto" cancelButton="none" />
				</view>
				<button class="mini-btn p010" type="default" style="backgroundColor:#397bff;color:#fff;" size="mini" @confirm="getPageList('onPullDownRefresh',navIndex)">查询</button>
			</view>
		</view>
		<view class="bottom-wrap">
		<scroll-view scroll-y="true" scroll-x="false" :style="{height:scrollH+'px'}" refresher-enabled="true" :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore">
		<!-- 内容切换 -->
		<view class="content" v-if="navIndex==0">
		<view class="pb130" v-if="List.length>0">
			<view class="p3020 bor_e8" v-for="item in List" @tap="navgetTo('pages/my/order_detail',item.orderNo,'')">
				<view class="uni-flex mb25">
					<view class="color-black">
						{{item.createDate}}
					</view>
					<view class="color-red" v-if="item.orderStatus == 1">待支付</view>
					<view class="color-red" v-if="item.orderStatus == 2">支付中</view>
					<view class="color-red" v-if="item.orderStatus == 3">支付成功</view>
					<view class="color-red" v-if="item.orderStatus == 4">已完结</view>
					<view class="color-red" v-if="item.orderStatus == 9">退款中</view>
					<view class="color-red" v-if="item.orderStatus == -1">已取消</view>
				</view>
				<view class="card-list is-flex">
					<image :src="item.coverUrl"></image>
					<view class="card-item">
						<view class="color-black mb25">行程：{{item.itineraryTitle}}</view>
						<view>路线：{{item.linesTitle}}</view>
						<view class="uni-flex">
							<view class="">
								<text>用户：{{item.nickName}}</text> 
							</view>
							<view class="">
								<text>总计：</text>
								<text class="color-red">￥{{item.orderAmount}}</text> 
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		</view>
		<!-- 内容切换 -->
		<view class="content" v-if="navIndex==1">
			<view class="" v-if="List.length>0">
				<view class="p3020 bor_e8" v-for="item in List" @tap="navgetTo('pages/my/order_detail',item.orderNo,'')">
					<view class="uni-flex mb25">
						<view class="color-black">
							{{item.createDate}}
						</view>
						<view class="color-red" v-if="item.orderStatus == 1">待支付</view>
						<view class="color-red" v-if="item.orderStatus == 2">支付中</view>
						<view class="color-red" v-if="item.orderStatus == 3">支付成功</view>
						<view class="color-red" v-if="item.orderStatus == 4">已完结</view>
						<view class="color-red" v-if="item.orderStatus == 9">退款中</view>
						<view class="color-red" v-if="item.orderStatus == -1">已取消</view>
					</view>
					<view class="card-list is-flex">
						<image :src="item.coverUrl"></image>
						<view class="card-item">
							<view class="color-black mb25">行程：{{item.itineraryTitle}}</view>
							<view>路线：{{item.linesTitle}}</view>
							<view class="uni-flex">
								<view class="">
									<text>用户：{{item.nickName}}</text> 
								</view>
								<view class="">
									<text>总计：</text>
									<text class="color-red">￥{{item.orderAmount}}</text> 
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 加载提示 -->
		 <view v-if="isLoading" class="tc mt100 mb100">{{loadMoreText}}</view>
		</scroll-view>
		</view>
	</view>
</template>

<script>
	import api from '@/common/api/webapi.js'; /*api*/
	export default {
		components: {
			
		},
		data() {
				const currentDate = this.getDate({format: true})
				return {
					starValue:0,
					navTop:44,
					showNavTop:88,
					bottomWrap:188,
					maxStar:5,
					single: "",
					keyword:'',
					navIndex:0,
					date: currentDate,
					startDate: this.getDate('start'),
					endDate: this.getDate('end'),
					scrollH:0,
					isRefreshing:false,
					isLoading:false,
					loadMoreText:"加载中...",
					List:[],
					totalMoney: '',
					param: {
						page: 1, //当前页
						limit: 10, //每页显示记录数
						PageCount: 0,
						keyword:'',
						startDate:'',
						endDate:'',
					},
				}
			},
		onReady() {
			// 获取可滚动区域的高度：视口高度 - tabbar切换卡高度就是剩余的内容可滚动的。
			//如果你使用取消了原生导航栏，记着把你自定义导航栏的高度也减掉哦
			uni.getSystemInfo({
				success: (res) => {
					this.scrollH = res.windowHeight - 188 - uni.upx2px(100)
				}
			})
		},
		computed: {
				// 日期范围已在data中直接初始化
			},
		watch: {

		},
		onShow() {
		},
		onLoad(option) {
				const app = getApp()
				this.navTop = app.globalData.navTop;
				this.showNavTop = this.navTop + 44;
				this.checkIndex(0);
			},
		mounted(){
		},
		methods: {
			back(){
				uni.switchTab({
					url:'/pages/my/my',
				});
			},
			checkIndex(index) {
					this.navIndex = index;
					// 重置分页和加载状态
					this.param.page = 1;
					this.isLoading = false;
					this.loadMoreText = "";
					// 切换标签页时显示加载提示
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					this.getPageList('onPullDownRefresh',this.navIndex);
				},
			bindDateChange: function(e) {
					this.date = e.detail.value;
					// 切换日期时显示加载提示
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					this.getPageList('onPullDownRefresh', this.navIndex);
				},
			getDate(type) {
					const date = new Date();
					let year = date.getFullYear();
					let month = date.getMonth() + 1;
					if (type === 'start') {
						// 起始日期为当前月份的前一年
						if (month === 1) {
							year -= 1;
							month = 12;
						} else {
							month -= 12;
							if (month <= 0) {
								year -= 1;
								month += 12;
							}
						}
					} else if (type === 'end') {
						// 结束日期为当前月份
						// 保持当前年月不变
					} else if (type && type.format) {
						// 返回当前年月格式
					}
					month = month > 9 ? month : '0' + month;
					return `${year}-${month}`;
				},
			// 城市选择器
			bindRegionChange: function(e) {
				this.region = e.detail.value;
			},
			// 星级点击事件
			starChange:function(e){
				this.starValue+1;
			},
			// 页面跳转
			navgetTo(page, param, type) {
				if (param != undefined) {
					type = type || '';
					let data = {
						data: param,
						page: type
					}
					uni.navigateTo({
						url: "/" + page + "?param=" + encodeURI(JSON.stringify(data))
					});
				} else {
					uni.navigateTo({
						url: "/" + page
					});
				}
			},
			onRefresh() {  // 下拉刷新
				console.log('下拉刷新被触发');
				this.isRefreshing = true;
				this.param.page = 1;
				console.log('准备调用getPageList，页码已重置为1');
				this.getPageList('onPullDownRefresh',this.navIndex);
			},
			onLoadMore() {  // 上拉加载
				if (this.isLoading) return;
				this.isLoading = true;
				this.param.page = (this.param.page + 1);
				if (this.param.page > this.param.PageCount) {
					this.isLoading = false; // 修复：将isLoading设置为false而不是true
					this.loadMoreText = "--到底啦--"
					return;
				}
				this.getPageList('onReachBottom',this.navIndex);
			},
			// 获取分页列表
			getPageList(type,navIndex) {
				console.log('getPageList方法被调用', {type, navIndex, page: this.param.page});
				let _this = this;
				// 从this.date中解析年和月，格式为YYYY-MM
				const dateParts = _this.date.split('-');
				const year = parseInt(dateParts[0]);
				const month = parseInt(dateParts[1]);
				// 设置startDate为所选月份的第一天
				const startDate = `${year}-${month.toString().padStart(2, '0')}-01`;
				// 获取所选月份的最后一天作为endDate
				const lastDay = new Date(year, month, 0).getDate();
				const endDate = `${year}-${month.toString().padStart(2, '0')}-${lastDay.toString().padStart(2, '0')}`;
				if(navIndex == 0){
					let requestData = {
						params: { 
							pageType:'INCONME',
							keyword:_this.param.keyword,//搜索关键字
							page: _this.param.page, //当前页
							size: _this.param.limit, //每页显示记录数
							startDate:startDate,
							endDate:endDate
						}
					}
					console.log('准备调用API.getOrderList', requestData);
					api.getOrderList(requestData).then(res => {
						// 隐藏加载提示
						uni.hideLoading();
						console.log('API.getOrderList响应', res);
						if (res.code === 0) {
							// 使用Vue.set确保响应式更新
							this.$set(this, 'loadMoreText', "");
							if (res.data.length > 0) {
								let pagelist = res.data;
								this.$set(this, 'param', Object.assign({}, this.param, {
									PageCount: Math.ceil(res.data.total / this.param.limit)
								}));
								if (type == "onReachBottom") {
									// 先创建新数组，确保Vue能检测到变化
									const newList = [..._this.List, ...pagelist];
									this.$set(this, 'List', newList);
								} else {
									// 直接设置新数组
									this.$set(this, 'List', pagelist);
								}
							}else{
								if(type == "onPullDownRefresh"){
									this.$set(this, 'List', []);
								}else if(type == "onReachBottom"){
									this.$set(this, 'param', Object.assign({}, this.param, {
										page: 1
									}));
									this.$set(this, 'loadMoreText', "--到底啦--");
								}
							}
						} else {
							console.log('API请求失败，状态码:', res.code);
							uni.showToast({
								icon: 'none',
								title: '获取订单列表失败'
							});
						}
						// 确保加载状态更新
						this.$nextTick(() => {
							this.$set(this, 'isRefreshing', false);
							this.$set(this, 'isLoading', false);
							if(type !== "onReachBottom"){
								this.$set(this, 'loadMoreText', "");
							}
						});
					}).catch(function(error){
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '网络请求失败'
						});
						console.error('API请求异常', error);
						// 确保加载状态更新
						this.$nextTick(() => {
							this.$set(this, 'isRefreshing', false);
							this.$set(this, 'isLoading', false);
							this.$set(this, 'loadMoreText', "");
						});
					})
				}else if(navIndex == 1){
					let requestData = {
						params: {
							pageType:'PAY',
							keyword:_this.param.keyword,//搜索关键字
							page: _this.param.page, //当前页
							size: _this.param.limit, //每页显示记录数
							startDate:startDate,
							endDate:endDate
						}
					}
					console.log('准备调用API.getOrderList', requestData);
					api.getOrderList(requestData).then(res => {
						// 隐藏加载提示
						uni.hideLoading();
						console.log('API.getOrderList响应', res);
						if (res.code === 0) {
							// 使用Vue.set确保响应式更新
							this.$set(this, 'loadMoreText', "");
							if (res.data.length > 0) {
								let pagelist = res.data;
								this.$set(this, 'param', Object.assign({}, this.param, {
									PageCount: Math.ceil(res.data.total / this.param.limit)
								}));
								if (type == "onReachBottom") {
									// 先创建新数组，确保Vue能检测到变化
									const newList = [..._this.List, ...pagelist];
									this.$set(this, 'List', newList);
								} else {
									// 直接设置新数组
									this.$set(this, 'List', pagelist);
								}
							}else{
								if(type == "onPullDownRefresh"){
									this.$set(this, 'List', []);
								}else if(type == "onReachBottom"){
									this.$set(this, 'param', Object.assign({}, this.param, {
										page: 1
									}));
									this.$set(this, 'loadMoreText', "--到底啦--");
								}
							}
						} else {
							console.log('API请求失败，状态码:', res.code);
							uni.showToast({
								icon: 'none',
								title: '获取订单列表失败'
							});
						}
						// 确保加载状态更新
						this.$nextTick(() => {
							this.$set(this, 'isRefreshing', false);
							this.$set(this, 'isLoading', false);
							if(type !== "onReachBottom"){
								this.$set(this, 'loadMoreText', "");
							}
						});
					}).catch(function(error){
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '网络请求失败'
						});
						console.error('API请求异常', error);
						// 确保加载状态更新
						this.$nextTick(() => {
							this.$set(this, 'isRefreshing', false);
							this.$set(this, 'isLoading', false);
							this.$set(this, 'loadMoreText', "");
						});
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		font-size: 14px;
		line-height: 24px;
	}

	.index-swiper {
		width: 100%;
		height: 670rpx;
	}

	.index-swiper image {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}
	
	.bottom-wrap{
		width: 100%;
		padding-top: 185rpx;
	}
	
	.is-flex{
		display: flex;
		align-items: center;
	}
	.flex1{
		flex: 1;
	}
	.mini-btn.p010{
		padding: 0 10px;
	}
	::v-deep.uni-searchbar__text-placeholder {
	    font-size: 12px;
	}
	::v-deep.uni-searchbar__box-search-input {
	    text-align: left;
	}
	.xf-wrap {
		position: relative;
		top: -60rpx;
		overflow: hidden;
	}

	.box-shadow {
		box-shadow: 2rpx 2px 2rpx $uni-text-color-grey8;
		background-color: #ffffff;
		border-radius: 20rpx;
	}

	.xf-wrap input {
		font-weight: bold;
	}

	.uni-flex {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
	}

	.uni-row {
		flex-direction: row;
	}
	.sticky {
		height: 200rpx;
		line-height: 85rpx;
		background-color: #ffffff;
		width: 100%;
		color: #888;
		position: fixed;
		top: -1rpx;
		left: 0;
		right: 0;
		z-index: 999;
		text-align: center;
	}

	.sticky text {
		color: $uni-text-color-light-blue;
		font-weight: bold;
		padding: 10rpx 15rpx;
	}
	.sticky text.active{
		color: $uni-text-color-blue;
		border-bottom: 2px solid $uni-text-color-blue;
	}
	.card-list.is-flex{
		display: flex;
		align-items: flex-start;
		image{
			width: 170rpx;
			height: 170rpx;
		}
		.card-item{
			flex: 1;
			margin-left: 25rpx;
		}
	}
	.pb130{
		padding-bottom: calc( 130rpx + max(env(safe-area-inset-bottom),20px));
	}
	.share-reward{
		.color-black{
			display: block;
			margin-bottom: 20rpx;
		}
		.is-flex{
			align-items: flex-start;
		}
		.color-gray{
			line-height: 1.8;
			text-align: justify;
			margin-left: 20rpx;
		}
	}
	
</style>